package com.googlecode.gamedroid.sockethelper;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.googlecode.gamedroid.R;

@SuppressLint("Registered")
public class DeviceList extends Activity
{
	public static ISocket getSocket(Intent intent)
	{
		if(!intent.hasExtra("type"))
			throw new IllegalArgumentException("No type extra");
		
		String type = intent.getStringExtra("type");
		
		if(type.equals("bluetooth"))
		{
			if(!(intent.hasExtra("bluetooth.device") && intent.hasExtra("bluetooth.uuid")))
				throw new IllegalArgumentException("Missing extras for type bluetooth");
			
			String device = intent.getStringExtra("bluetooth.device");
			
			return new SocketBluetooth(device, intent.getStringExtra("bluetooth.uuid"));
		}
		if(type.equals("network"))
		{
			if(!(intent.hasExtra("network.host") && intent.hasExtra("network.port")))
				throw new IllegalArgumentException("Missing extras for type network");
			
			String host = intent.getStringExtra("network.host");
			int port = intent.getIntExtra("network.port", -1);
			if(port == -1)
				throw new IllegalArgumentException("Port is not an integer");
			
			return new SocketNetwork(host, port);
		}
		
		throw new IllegalArgumentException("Unknown type");
	}
	
	private DeviceAdapter adapter;
	private TextView editHost, editPort;
	
	private ListView listView;
	
	private void cancel()
	{
		Intent intent = new Intent();
		intent.putExtra("type", "cancel");
		setResult(RESULT_OK, intent);
		finish();
	}
	
	private void selectBluetoothSocket(int position)
	{
		BluetoothDevice device = (BluetoothDevice) adapter.getItem(position);
		
		Intent intent = new Intent();
		intent.putExtra("type", "bluetooth");
		intent.putExtra("bluetooth.device", device.getAddress());
		setResult(RESULT_OK, intent);
		finish();
	}
	
	private void selectNetworkSocket()
	{
		String host = editHost.getText().toString();
		if(host.equals(""))
		{
			editHost.requestFocus();
			return;
		}
		
		String port = editPort.getText().toString();
		if(port.equals(""))
		{
			editPort.requestFocus();
			return;
		}
		
		int portNo;
		try
		{
			portNo = Integer.parseInt(port);
		}
		catch(NumberFormatException e)
		{
			editPort.requestFocus();
			return;
		}
		
		Intent intent = new Intent();
		intent.putExtra("type", "network");
		intent.putExtra("network.host", host);
		intent.putExtra("network.port", portNo);
		setResult(RESULT_OK, intent);
		finish();
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		
		Intent request = getIntent();
		
		if(request.hasExtra("is_cancelable"))
			getActionBar().setDisplayHomeAsUpEnabled(true);
		
		adapter = new DeviceAdapter(this);
		
		setContentView(R.layout.activity_device_list);
		
		View network = getLayoutInflater().inflate(R.layout.network, null);
		
		this.setProgressBarIndeterminateVisibility(false);
		
		listView = (ListView) findViewById(R.id.list_view);
		listView.addHeaderView(network);
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(new OnItemClickListener()
		{
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id)
			{
				DeviceList.this.selectBluetoothSocket(position - 1);
			}
		});
		
		OnEditorActionListener onEditorAction = new OnEditorActionListener()
		{
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event)
			{
				if(actionId == EditorInfo.IME_ACTION_DONE)
				{
					selectNetworkSocket();
					return true;
				}
				return false;
			};
		};
		
		editHost = (TextView) findViewById(R.id.edit_host);
		editPort = (TextView) findViewById(R.id.edit_port);
		
		editHost.setOnEditorActionListener(onEditorAction);
		editPort.setOnEditorActionListener(onEditorAction);
		
		if(request.hasExtra("default.host"))
			editHost.setText(request.getStringExtra("default.host"));
		if(request.hasExtra("default.port"))
			editPort.setText(String.format("%d", request.getIntExtra("default.port", 0)));
	}
	
	@Override
	protected void onStart()
	{
		super.onStart();
		adapter.onStart();
	}
	
	@Override
	protected void onStop()
	{
		super.onStop();
		adapter.onStop();
	}
	
	public void onDiscoveryFinished()
	{
		this.setProgressBarIndeterminateVisibility(false);
	}
	
	public void onDiscoveryStarted()
	{
		this.setProgressBarIndeterminateVisibility(true);
	}
	
	public void onNetworkConnectionOpen(View v)
	{
		selectNetworkSocket();
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		switch(item.getItemId())
		{
			case android.R.id.home:
				cancel();
				return true;
				
			default:
				return super.onOptionsItemSelected(item);
		}
	}
	
	public void requestEnableBluetooth()
	{
		Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
		startActivity(intent);
	}
}
